package cn.i96688.scanclient.ui;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;

import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

import com.alibaba.fastjson.JSONObject;
import cn.i96688.scanclient.barcode.BarcodeConsumer;
import cn.i96688.scanclient.barcode.BarcodeProducter;
import cn.i96688.scanclient.barcode.ScanBarcodeListener;
import cn.i96688.scanclient.bean.MerInfo;
import cn.i96688.scanclient.bean.PayLog;
import cn.i96688.scanclient.ui.PayDialogConfig.SaveDataListener;
import cn.i96688.scanclient.ui.ScanPayForm.PaySucListener;
import cn.i96688.scanclient.utils.AppEnv;
import cn.i96688.scanclient.utils.BarcodeUtil;
import cn.i96688.scanclient.utils.Constants;
import cn.i96688.scanclient.utils.LocalStore;
/**
 * 系统主界面
 * @author xys
 *
 */
public class MainForm extends SuperForm implements WindowListener{
	private static final long serialVersionUID = 1L;
	public static final Image icon = Toolkit.getDefaultToolkit().getImage(MainForm.class.getResource("/icon.png"));
	// Variables declaration - do not modify
	private PopupMenu pop;
	private TrayIcon trayicon;
	
	private MenuItem open, close;
	private JMenuItem jclose,jdebug,jlogout,jPayDialogSet;
	private JMenuItem jscanTest;
	private ScanPayForm payForm;
	private CurOrderListPane orderListPane;
	private StatusLine statusLine;

	// End of variables declaration

	/** Creates new form MainFrame */
	public MainForm() {
		setTitle();
		setIconImage(icon);
		initComponents();
		initTray();
		initMenu();
		
		this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		

//		setExtendedState(JFrame.MAXIMIZED_BOTH);
		Dimension screenSize =Toolkit.getDefaultToolkit().getScreenSize();
		int width=(int)(screenSize.width*0.6);
		int height=(int)(screenSize.height*0.8);
		Dimension size=getSize();
		size.height=height;
		size.width=width;
		setSize(size);
		
		addWindowListener(this);
		startScanBarcode();
		Thread.currentThread().setName(Constants.APP_NAME);
		this.addMouseListener(this);
		
		payForm.setPaySucListener(new PaySucListener(){
			@Override
			public void insertFirst(JSONObject data) {
				orderListPane.insertRowFirst(data);
			}});
		orderListPane.addTableModelListener(statusLine);
		orderListPane.loadData();
		
	}
	
	private void setTitle(){
		setTitle("扫码支付 :: "+MerInfo.getInstance().getMerInf().getString("merName")+" :: 设备编码（"+MerInfo.getInstance().getMerInf().getString("deviceCode")+"）");
	}
	
	private void initMenu(){
		JMenuBar menuBar=new JMenuBar();
		setJMenuBar(menuBar);
		JMenu fileMenu = new JMenu();
		menuBar.add(fileMenu);
		fileMenu.setText("文件");
		
		JMenu helpMenu = new JMenu();
		menuBar.add(helpMenu);
		helpMenu.setText("帮助");
		
		jclose=new JMenuItem("关闭");
		fileMenu.add(jclose);
		jlogout=new JMenuItem("注销");
		fileMenu.add(jlogout);
		
		jdebug=new JMenuItem("调试");
		helpMenu.add(jdebug);
		
		jPayDialogSet=new JMenuItem("支付框设置");
		helpMenu.add(jPayDialogSet);
		
		jscanTest=new JMenuItem("支付键盘");
		helpMenu.add(jscanTest);
		
		jclose.addActionListener(this);
		jlogout.addActionListener(this);
		jdebug.addActionListener(this);
		jPayDialogSet.addActionListener(this);
		jscanTest.addActionListener(this);
	}
	@Override
	public void dispose(){
		super.dispose();
		AppEnv.stopServer();
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		//用来测试
//		payForm.showForm();
	}
	
	private void startScanBarcode(){
		payForm=new ScanPayForm();
		BarcodeProducter.getInstance().startProduct();
		BarcodeConsumer.getInstance().setScanBarcodeListener(
				new ScanBarcodeListener(){
					@Override
					public void consume(String barcode) {
						if(BarcodeUtil.check(barcode)){
							payForm.setBarcode(barcode);
							payForm.showForm();
						}else{
							PayLog.getInstance().addLog("不支持的条码类型（非微信/支付宝条码）："+barcode);
						}
					}
				});
	}

	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {
		orderListPane=new CurOrderListPane();
		setLayout(new BorderLayout());
		add(orderListPane,BorderLayout.CENTER);
		statusLine=new StatusLine();
		statusLine.setMessage(" ");
		add(statusLine,BorderLayout.SOUTH);
	}

	private void initTray(){
		pop = new PopupMenu();
		open = new MenuItem("\u6253\u5F00");
		open.addActionListener(this);

		close = new MenuItem("\u5173\u95ED");
		close.addActionListener(this);

		pop.add(open);
		pop.add(close);

		if (SystemTray.isSupported()) {
			SystemTray tray = SystemTray.getSystemTray();
			Image icon2=icon.getScaledInstance(16, 16, java.awt.Image.SCALE_DEFAULT);
			trayicon = new TrayIcon(icon2, "扫码支付", pop);
			trayicon.addMouseListener(new MouseAdapter() {

				public void mouseClicked(MouseEvent e) {
					/*
					if (getExtendedState() == JFrame.ICONIFIED) {
						openFrame();// 还原窗口
					}
					else {
						// 设置窗口状态(最小化至托盘)
						setExtendedState(JFrame.ICONIFIED);
					}*/
					openFrame();// 显示
				}
			});

			try {
				tray.add(trayicon);
			} catch (AWTException e) {
				e.printStackTrace();
			}
		}
		pack();
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == open) {//打开
			openFrame();
		}else if (e.getSource() == close || e.getSource()==jclose) {//关闭
			System.exit(-1);
		}else if(e.getSource()==jlogout){//注销
			LoginForm paramForm=new LoginForm(new LoginForm.SaveListener(){
				@Override
				public void save(boolean status) {
					orderListPane.refresh();
					MainForm.this.setTitle();
				}});
			paramForm.showForm();
		}else if(e.getSource()==jdebug){//调试
			new DebugDialog(this).showForm();
		}else if(e.getSource()==jPayDialogSet){
			PayDialogConfig pd=new PayDialogConfig(this);
			int w=payForm.getBounds().width;
			int h=payForm.getBounds().height;
			pd.setSaveDataListener(new SaveDataListener(){
				@Override
				public void save(JSONObject json) {
					LocalStore.getInstance().writePayDialogConfig(json);
					payForm.updateConfig(json);
				}});
			
			pd.setPaySize(w, h,payForm.getAmountSize(),payForm.getKeyboardSize());
			pd.showForm();
		}
	}

	public void openFrame() {
		// 设置窗口状态(在最小化状态弹出显示)
		this.showForm();
		this.setFocusable(true);
		setExtendedState(MainForm.NORMAL);
//		setExtendedState(JFrame.MAXIMIZED_BOTH);
	}

	public void windowActivated(WindowEvent arg0) {

	}

	public void windowClosed(WindowEvent arg0) {
		BarcodeProducter.getInstance().stopProduct();
		dispose();
	}

	public void windowClosing(WindowEvent arg0) {
		setExtendedState(MainForm.ICONIFIED | getExtendedState());
	}

	public void windowDeactivated(WindowEvent arg0) {
	}

	public void windowDeiconified(WindowEvent arg0) {
	}

	// 窗口最小化
	public void windowIconified(WindowEvent arg0) {
	}

	public void windowOpened(WindowEvent arg0) {

	}
}
